﻿using OpenCvSharp.Extensions;
using OpenCvSharp;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows;

namespace WheelClean2.ViewModels
{
    class MonitorViewModel : BindableBase, INavigationAware
    {

        private readonly IRegionManager _regionManager;
        private readonly INavigationAware _navigationAware;
        private ImageSource _cImageSource;
        public ImageSource CImageSource
        {
            get { return _cImageSource; }
            set { SetProperty(ref _cImageSource, value); }
        }

        MonitorViewModel(IRegionManager contentRegion)
        {
            _regionManager = contentRegion;

            Thread threadA = new Thread(run_cap);
            threadA.Start();
        }

        void run_cap()
        {
            Mat src = new Mat();
            FrameSource frame = Cv2.CreateFrameSource_Camera(0);
            while (true)
            {
                frame.NextFrame(src);
                System.Drawing.Bitmap bitmap = BitmapConverter.ToBitmap(src);
                Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    CImageSource = BitmapToBitmapImage(bitmap);
                });
                Thread.Sleep(100);
            }



        }

        public System.Windows.Media.Imaging.BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
        {
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            System.Windows.Media.Imaging.BitmapImage bit3 = new System.Windows.Media.Imaging.BitmapImage();
            bit3.BeginInit();
            bit3.StreamSource = ms;
            bit3.EndInit();
            return bit3;
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {

        }
    }
}
